<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\OverSeasIn;

use App\Models\OverSeasBa\InventoryBox;
use App\Models\OverSeasBa\InventoryBoxFNSku;
use App\Models\OverSeasIn\DeliveryBox;
use App\Models\OverSeasIn\DeliveryBoxDetail;
use Illuminate\Support\Facades\DB;
class ReceiveExAjax {

    /**
     * 入库
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchReceive($param){
        try{
            DB::beginTransaction();
            $dealAt = date('Y-m-d H:i:s');
            $exist = [];
            foreach ($param as $item){
                if(in_array($item['detail_key'],$exist)){
                    continue;
                }else{
                    $exist[] = $item['detail_key'];
                }
                list($deliveryNo,$boxNo) = explode('_',$item['detail_key']);
                $deliveryBoxes = DeliveryBox::query()
                    ->where('delivery_no',$deliveryNo)
                    ->where('box_no',$boxNo)
                    ->get();
                foreach ($deliveryBoxes as $deliveryBox){
                    $total = $deliveryBox->total;
                    $storageTotal = $deliveryBox->storage_total;
                    $thisStorageTotal = min($total - $storageTotal,$item['this_storage_num']);
                    $deliveryBox->storage_total += $thisStorageTotal;
                    if($deliveryBox->storage_total > 0){
                        if($total == $deliveryBox->storage_total){
                            $deliveryBox->status = 3;
                            $deliveryBox->ex_deal = 2;
                        }else{
                            $deliveryBox->status = 2;
                        }
                    }
                    $deliveryBox->save();
                    //更新明细
                    $this->_upBoxDetail($deliveryBox->id,$total,$storageTotal,$thisStorageTotal,$dealAt,2);
                    //更新库存
                    $this->_upInventoryBox($deliveryBox,$dealAt);
                    //更新库存FnSku
                    $num = $thisStorageTotal * $deliveryBox->num_per_box;
                    $this->_upInventoryBoxFnSku($deliveryBox->warehouse_id,$deliveryBox->account_id,$deliveryBox->fnsku,$deliveryBox->psku_id,$num);
                }
            }
            DB::commit();
            return response()->json(['status' => true,'message' => '操作成功！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 正常入库-更新FNSKU库存
     * @param $warehouseId
     * @param $accountId
     * @param $fnSku
     * @param $pSkuId
     * @param $num
     */
    protected function _upInventoryBoxFnSku($warehouseId,$accountId,$fnSku,$pSkuId,$num){
        $inventory = InventoryBoxFNSku::query()
            ->where('warehouse_id',$warehouseId)
            ->where('account_id',$accountId)
            ->where('fnsku',$fnSku)
            ->lockForUpdate()
            ->first();
        if(!$inventory){
            InventoryBoxFNSku::query()->create(
                [
                    'warehouse_id' => $warehouseId,
                    'account_id' => $accountId,
                    'fnsku' => $fnSku,
                    'psku_id' => $pSkuId,
                    'instant' => $num,
                ]
            );
        }else{
            $inventory->instant += $num;
            $inventory->transit -= min($inventory->transit,$num);
            $inventory->save();
        }
    }

    /**
     * 正常入库-更新BOX库存
     * @param $deliveryBox
     * @param $storageAt
     */
    protected function _upInventoryBox($deliveryBox,$storageAt){
        InventoryBox::query()->updateOrCreate(
            [
                'batch_no' => $deliveryBox->batch_no,
                'box_no' => $deliveryBox->box_no,
                'fnsku' => $deliveryBox->fnsku,
                'warehouse_id' => $deliveryBox->warehouse_id,
            ],
            [
                'delivery_box_id' => $deliveryBox->id,
                'account_id' => $deliveryBox->account_id,
                'area_id' => $deliveryBox->area_id,
                'storage_total' => $deliveryBox->storage_total,
                'num_per_box' => $deliveryBox->num_per_box,
                'psku_id' => $deliveryBox->psku_id,
                'storage_at' => $storageAt,
            ]
        );
    }

    /**
     * 回写boxDetail数据
     * @param $deliveryBoxId
     * @param $total
     * @param $storageTotal
     * @param $thisStorageTotal
     * @param $dealAt
     * @param int $status
     */
    protected function _upBoxDetail($deliveryBoxId,$total,$storageTotal,$thisStorageTotal,$dealAt,$status = 2){
        for ($i = 1;$i <= $thisStorageTotal;$i++){
            $pIndex = $i + $storageTotal;
            if($pIndex > $total)break;
            $boxDetail = DeliveryBoxDetail::query()
                ->where('delivery_box_id',$deliveryBoxId)
                ->where('status',1)
                ->where('p_index',$pIndex)
                ->first();
            if($boxDetail){
                $boxDetail->status = $status;
                $boxDetail->deal_at = $dealAt;
                $boxDetail->save();
            }
        }
    }

    /**
     * 赔付处理
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchPaid($param){
        try{
            DB::beginTransaction();
            $dealAt = date('Y-m-d H:i:s');
            $exist = [];
            foreach ($param as $item){
                if(in_array($item['detail_key'],$exist)){
                    continue;
                }else{
                    $exist[] = $item['detail_key'];
                }
                list($deliveryNo,$boxNo) = explode('_',$item['detail_key']);
                $deliveryBoxes = DeliveryBox::query()
                    ->where('delivery_no',$deliveryNo)
                    ->where('box_no',$boxNo)
                    ->get();
                foreach ($deliveryBoxes as $deliveryBox){
                    $deliveryBox->ex_deal = 3;
                    $deliveryBox->save();
                    $total = $deliveryBox->total;
                    $storageTotal = $deliveryBox->storage_total;
                    $thisStorageTotal = $total - $storageTotal;
                    //更新明细
                    $this->_upBoxDetail($deliveryBox->id,$total,$storageTotal,$thisStorageTotal,$dealAt,3);
                    //更新库存FnSku
                    $num = $thisStorageTotal * $deliveryBox->num_per_box;
                    $this->_up2InventoryFnSku($deliveryBox->warehouse_id,$deliveryBox->account_id,$deliveryBox->fnsku,$num);
                }
            }
            DB::commit();
            return response()->json(['status' => true,'message' => '操作成功！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 赔付处理-更新FNSKU库存
     * @param $warehouseId
     * @param $accountId
     * @param $fnSku
     * @param $num
     */
    protected function _up2InventoryFnSku($warehouseId,$accountId,$fnSku,$num){
        $inventory = InventoryBoxFNSku::query()
            ->where('warehouse_id',$warehouseId)
            ->where('account_id',$accountId)
            ->where('fnsku',$fnSku)
            ->lockForUpdate()
            ->first();
        if($inventory){
            $inventory->transit -= min($inventory->transit,$num);
            $inventory->save();
        }
    }
}
